<script setup>
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app';
import { ref, unref } from 'vue';
import { getAuthorization } from '@/router/auth.js';
import appUpdate from '@/utils/update.js';
import { setMessageBadge } from '@/hooks/com.js';
import { getMonthAllAppMes } from '@/api/message.js';

onLaunch(() => {
	console.log('App Launch');
	// 没有token调整登录页面
	if (!getAuthorization('accessToken')) {
		uni.reLaunch({
			url: '/pages/login/login',
			success: () => {
				// #ifdef APP-PLUS
				plus.navigator.closeSplashscreen();
				// #endif
			}
		});
		return;
	} else {
		//存在则关闭启动页进入首页
		// #ifdef APP-PLUS
		plus.navigator.closeSplashscreen();
		// #endif
	}
});

let idList = [];

function showNotification(message) {
	uni.createPushMessage({
		title: message.messageTitle,
		content: message.messageInfo,
		icon: 'static/index/logo.png'
	});
}
const messagePush = () => {
	getMonthAllAppMes().then((res) => {
		if (res.data.length) {
			res.data.forEach((item) => {
				if (!idList.includes(item.id)) {
					// #ifdef APP-PLUS
					showNotification(item);
					idList.push(item.id);
					// #endif
				}
			});
		}
	});
};

let timer = ref(null);
onShow(() => {
	if (getAuthorization('accessToken')) {
		appUpdate(); // APP自动更新
		setMessageBadge();
		messagePush();
		timer.value = setInterval(() => {
			setMessageBadge();
			messagePush();
		}, 10 * 1000);
	}
});
onHide(() => {
	if (unref(timer)) {
		clearInterval(unref(timer));
		timer.value = null;
	}
});
</script>
<style lang="scss">
/*每个页面公共css */
@import '@/uni_modules/uview-plus/index.scss';
/* #ifndef APP-NVUE */
@import '@/style/index.scss';
/* #endif */
</style>
